package com.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mh.dao.MbtiTestDao;
import com.mh.dto.R;
import com.mh.pojo.MbtiTest;
import com.mh.service.MbtiTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * MBTI题库(MbtiTest)表服务实现类
 *
 * @author zmh
 * @since 2024-09-26 20:39:00
 */
@Service
public class MbtiTestServiceImpl extends ServiceImpl<MbtiTestDao, MbtiTest> implements MbtiTestService {

    @Autowired
    private MbtiTestDao mbtiTestDao;

    /**
     * 分页查询
     *
     * @param page 查询页数
     * @param size 一页显示条数
     * @return ·
     */
    public R<Page<MbtiTest>> getAllByPage(int page, int size) {
        Page<MbtiTest> mbtiTestPage = new Page<>(page, size);
        LambdaQueryWrapper<MbtiTest> queryWrapper = new LambdaQueryWrapper<>();
        //TODO 查询条件定制
        return R.success(mbtiTestDao.selectPage(mbtiTestPage, queryWrapper));
    }

    @Override
    public void importMbtiTestData(String filePath) {
        List<MbtiTest> mbtiTests = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 处理每一行，提取问题和选项
                if (line.startsWith("Q: ")) {
                    // 提取问题部分
                    String question = line.substring(3, line.indexOf("a.")).trim();

                    // 提取选项 A 和选项 B
                    String optionsPart = line.substring(line.indexOf("a."));
                    String[] options = optionsPart.split("；|;"); // 以分号或英文分号分隔
                    String optionA = options[0].substring(3).trim(); // 去掉选项 A 前缀
                    String optionB = options[1].substring(3).trim(); // 去掉选项 B 前缀

                    // 创建 MbtiTest 对象并设置值
                    MbtiTest mbtiTest = new MbtiTest();
                    mbtiTest.setQuestion(question);
                    mbtiTest.setOptionA(optionA);
                    mbtiTest.setOptionB(optionB);
                    mbtiTests.add(mbtiTest);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 批量插入数据库
        if (!mbtiTests.isEmpty()) {
            mbtiTestDao.insert(mbtiTests);
        }
    }

    @Override
    public R<List<MbtiTest>> getAll() {
        List<MbtiTest> mbtiTests = mbtiTestDao.selectList(null);
        return R.success(mbtiTests);
    }
}

